﻿//Copyright (C) <2013>  <jonathan cleeve norton> All Rights Reserved 
//Contact jon.norton@fin-plus.co.uk website <http://www.fin-plus.co.uk/>
using FinPlusAssembler;
using FinPlusInterfaces;

namespace FinPlusCompCore
{
    public class FinPlusConnectDB : FinPlusComponent
    {
        [State(Test = true)]
        public override bool IsValid { get; set; }
        [State(Test = true)]
        public override string TestString { get { return Adapter.ToString(); } }
        public override IPods Adapter { get { return _pods; } }
    
        private readonly IQuery _query;
        private readonly IPods _pods;
        private readonly IConnDatabase _conn;
        private readonly ConType _conType;

        //construct
        public FinPlusConnectDB(string group, string where = "", QueryType queryType = QueryType.Select, string dateTime = "", ConType conType = ConType.All)
        {
            _conn =  IOC.New<IConnDatabase>();
            _conType = conType;

            switch (queryType)
            {
                case QueryType.SavePod: _query = _conn.SavePod(group, where, ConType.NewAndAmend); break;
                case QueryType.Select: _query = _conn.Select(group, where, ConType.NewAndAmend); break;
                case QueryType.SelectAsOf: _query = _conn.SelectAsOf(group, dateTime.ParseDateTime(), where, _conType); break;
                case QueryType.SelectFrom: _query = _conn.SelectFrom(group, dateTime.ParseDateTime(), where, _conType); break;
            }

            _pods = _query.Values;
            _pods.PodUpdate += Bean_Update;

            IsValid = true;
        }

        public FinPlusConnectDB(string xmlPath)
        {
            _pods = IOC.New<IPods>(xmlPath);

            IsValid = true;
        }

        //common control interface
        public override void Dispose()
        {
            if (_query != null)
                _query.Dispose();

            if (_conn != null)
                _conn.Dispose();
        }

        //public
        public void Save(IPod pod)
        {
            if (_conn != null && pod != null)
                _conn.Save(pod);
        }

        //private
        private void Bean_Update(object s, BeanEventArgs a)
        {
            var pod = (IPod)s;
            
            //TODO REMOVE TEMP KEEP DB SMALL
            if (!pod.Name.Equals("Audit"))
                return;

            if (_conn != null )
                _conn.Save(pod);
        }
    }
}
